package com.xxjqr.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxjqr.rbac.entity.pojo.TbDept;
import com.xxjqr.rbac.entity.dto.DeptDto;
import com.xxjqr.rbac.entity.vo.DeptVo;
import com.xxjqr.rbac.mapper.TbDeptMapper;
import com.xxjqr.rbac.service.TbDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxjqr.rbac.util.SnowIdUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 丁昌江
 * @since 2021-02-02
 */
@Service
public class TbDeptServiceImpl extends ServiceImpl<TbDeptMapper, TbDept> implements TbDeptService {

    @Override
    public int addDept(DeptDto dto) {
        TbDept tbDept = new TbDept();
        BeanUtils.copyProperties(dto, tbDept);
        tbDept.setId(SnowIdUtil.nextId());
        return baseMapper.insert(tbDept);
    }

    @Override
    public List<DeptVo> getDeptTree(String deptName, Integer status) {
        LambdaQueryWrapper<TbDept> queryWrapper = new LambdaQueryWrapper<TbDept>()
                .eq(TbDept::getIsDelete, 0);

        if (StringUtils.hasLength(deptName)) {
            queryWrapper.like(TbDept::getName,deptName);
        }
        if (status != null) {
            queryWrapper.like(TbDept::getStatus,status);
        }

        List<TbDept> allDept = baseMapper.selectList(queryWrapper);

        return transferDeptVo(allDept, 0L);
    }

    @Override
    public int delDept(Long id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public Boolean editDept(DeptDto dto) {
        TbDept tbDept = new TbDept();
        BeanUtils.copyProperties(dto, tbDept);
        return updateById(tbDept);
    }

    private List<DeptVo> transferDeptVo(List<TbDept> allDept, Long parentId) {
        List<DeptVo> resultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(allDept)) {
            for (TbDept source : allDept) {
                if (parentId.longValue() == source.getParentId().longValue()) {
                    DeptVo deptVo = new DeptVo();
                    BeanUtils.copyProperties(source, deptVo);
                    //递归查询子菜单，并封装信息
                    List<DeptVo> childList = transferDeptVo(allDept, source.getId());
                    if (!CollectionUtils.isEmpty(childList)) {
                        deptVo.setChildDept(childList);
                    }
                    resultList.add(deptVo);
                }
            }
        }
        return resultList;
    }
}
